<template>
  <view class="profile-container">
    <view class="page-title">个人信息</view>
    <view class="card">
      <view class="row">
        <text class="label">昵称</text>
        <text class="value">{{ user.patientName || name || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">手机号</text>
        <text class="value">{{ user.phone || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">性别</text>
        <text class="value">{{ sexText }}</text>
      </view>
      <view class="row">
        <text class="label">年龄</text>
        <text class="value">{{ user.age != null ? user.age : '-' }}</text>
      </view>
      <view class="row">
        <text class="label">民族</text>
        <text class="value">{{ user.nation || '-' }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      user: {}
    }
  },
  computed: {
    ...mapGetters(['name', 'id', 'token']),
    sexText() {
      const v = this.user.sex
      // 兼容数值与字符串
      if (v === 1 || v === '1' || v === '女' || v === 'F' || v === 'f') return '女'
      if (v === 0 || v === '0' || v === '男' || v === 'M' || v === 'm') return '男'
      return '-'
    }
  },
  async onLoad() {
    // 个人信息页改为仅从本地缓存读取，不再请求后端
    console.log('[Profile] 仅从本地缓存(profileInfo/userInfo)读取，展示 昵称/手机号/性别/年龄/民族')
    await this.load()
  },
  onShow() {
    // 返回本页时也重新读取，避免显示旧缓存
    this.load()
  },
  methods: {
    async load() {
      // 1) 优先读取 mine/index.vue 持久化的完整信息
      const cached = uni.getStorageSync('profileInfo')
      if (cached && Object.keys(cached).length) {
        // 规范化性别
        const norm = { ...cached }
        const v = norm.sex
        if (v === '男' || v === 'M' || v === 'm') norm.sex = 0
        else if (v === '女' || v === 'F' || v === 'f') norm.sex = 1
        console.log('[Profile] 使用缓存 sex=', norm.sex, 'raw=', cached.sex)
        this.user = norm
        return
      }

      // 2) 兜底：从 userInfo + vuex 拼装最少字段（不发请求）
      const basic = uni.getStorageSync('userInfo') || {}
      const assembled = {
        patientName: basic.nickname || this.name || '-',
        phone: '',
        sex: null,
        age: '',
        nation: ''
      }
      this.user = assembled
      if (!this.token) {
        uni.showToast({ title: '未登录，展示本地缓存', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  background: #f5f5f5;
  min-height: 100vh;
}
.page-title { padding: 24rpx 30rpx; color: #333; font-weight: 600; font-size: 32rpx; }
.card {
  background: #fff;
  margin: 20rpx 0;
}
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.row:last-child { border-bottom: 0; }
.label { color: #666; font-size: 28rpx; }
.value { color: #333; font-size: 28rpx; max-width: 60%; text-align: right; }
</style>
